<?php
// 在 batch_operations.php 开头添加
error_log("=== 批量操作调试信息 ===");
error_log("POST数据: " . print_r($_POST, true));
error_log("FILES数据: " . print_r($_FILES, true));
error_log("action: " . ($_POST['action'] ?? '未设置'));
error_log("settlement_type: " . ($_POST['settlement_type'] ?? '未设置'));
error_log("settlement_amount: " . ($_POST['settlement_amount'] ?? '未设置'));
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 获取POST数据
$action = $_POST['action'] ?? '';
$orderIdsJson = $_POST['order_ids'] ?? '[]';
$settlementType = $_POST['settlement_type'] ?? 'commission';
$settlementAmount = isset($_POST['settlement_amount']) ? floatval($_POST['settlement_amount']) : null;
$settlementInfo = $_POST['settlement_info'] ?? '批量结算操作';

// 新增：回款相关参数
$refundAmount = $_POST['refund_amount'] ?? null;
$refundInfo = $_POST['refund_info'] ?? '批量回款操作';

// 解析订单ID
$orderIds = json_decode($orderIdsJson, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($orderIds)) {
    echo json_encode(['success' => false, 'message' => '请选择要操作的订单']);
    exit;
}

// 确保所有订单ID都是整数
$orderIds = array_map('intval', $orderIds);
$orderIds = array_filter($orderIds);

// 调试日志
error_log("批量操作参数: action={$action}, settlementType={$settlementType}, settlementAmount={$settlementAmount}, orderCount=" . count($orderIds));

$db = getDB();
$successCount = 0;
$errorCount = 0;
$errors = [];

// 处理文件上传（结算截图或回款截图）
$uploadedScreenshots = [];
$uploadType = 'settlement_screenshot'; // 默认上传类型

if (isset($_FILES['settlement_screenshots']) && is_array($_FILES['settlement_screenshots']['name'])) {
    foreach ($_FILES['settlement_screenshots']['name'] as $key => $name) {
        if ($_FILES['settlement_screenshots']['error'][$key] === UPLOAD_ERR_OK) {
            $file = [
                'name' => $name,
                'type' => $_FILES['settlement_screenshots']['type'][$key],
                'tmp_name' => $_FILES['settlement_screenshots']['tmp_name'][$key],
                'error' => $_FILES['settlement_screenshots']['error'][$key],
                'size' => $_FILES['settlement_screenshots']['size'][$key]
            ];
            
            $uploadResult = uploadFile($file, $uploadType);
            if ($uploadResult['success']) {
                $uploadedScreenshots[] = $uploadResult['filename'];
            }
        }
    }
}

// 处理回款截图上传
if (isset($_FILES['refund_screenshots']) && is_array($_FILES['refund_screenshots']['name'])) {
    foreach ($_FILES['refund_screenshots']['name'] as $key => $name) {
        if ($_FILES['refund_screenshots']['error'][$key] === UPLOAD_ERR_OK) {
            $file = [
                'name' => $name,
                'type' => $_FILES['refund_screenshots']['type'][$key],
                'tmp_name' => $_FILES['refund_screenshots']['tmp_name'][$key],
                'error' => $_FILES['refund_screenshots']['error'][$key],
                'size' => $_FILES['refund_screenshots']['size'][$key]
            ];
            
            $uploadResult = uploadFile($file, 'settlement_screenshot'); // 使用相同的上传类型
            if ($uploadResult['success']) {
                $uploadedScreenshots[] = $uploadResult['filename'];
            }
        }
    }
}

// 处理每个订单
foreach ($orderIds as $orderId) {
    try {
        // 获取订单信息
        $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();
        
        if (!$order) {
            throw new Exception("订单 {$orderId} 不存在");
        }
        
        // 开始事务
        $db->beginTransaction();
        
        switch ($action) {
            case 'delete':
                // 删除订单
                deleteOrderAndRelatedData($orderId);
                $successCount++;
                break;
                
            case 'refund':
                // 退还订单
                if ($order['status'] == 'refunded') {
                    throw new Exception("订单 {$orderId} 已退还");
                }
                
                $stmt = $db->prepare("UPDATE orders SET status = 'refunded', is_returned = 1, is_registered = 1, admin_id = ?, updated_at = NOW() WHERE id = ?");
                if (!$stmt->execute([$_SESSION['user_id'], $orderId])) {
                    throw new Exception("订单 {$orderId} 更新失败");
                }
                
                // 记录操作
                recordOrderOperation($orderId, 'return', 0, '批量退还操作', $uploadedScreenshots, $_SESSION['user_id']);
                $successCount++;
                break;
                
            case 'register':
                // 批量登记订单
                if ($order['is_registered'] == 1) {
                    throw new Exception("订单 {$orderId} 已登记");
                }
                
                $stmt = $db->prepare("UPDATE orders SET is_registered = 1, admin_id = ?, updated_at = NOW() WHERE id = ?");
                if (!$stmt->execute([$_SESSION['user_id'], $orderId])) {
                    throw new Exception("订单 {$orderId} 更新失败");
                }
                
                // 记录操作
                recordOrderOperation($orderId, 'register', 0, '批量登记操作', $uploadedScreenshots, $_SESSION['user_id']);
                $successCount++;
                break;
                
            case 'settle':
                // 结算订单 - 简化逻辑
                $operationType = ($settlementType == 'commission') ? 'settle_principal' : 'settle_commission';
                $dbSettlementType = ($settlementType == 'commission') ? 'principal' : 'principal_commission';
                
                // 计算结算金额
                if ($settlementAmount !== null && $settlementAmount > 0) {
                    $finalAmount = $settlementAmount;
                } else {
                    // 自动计算金额
                    if ($settlementType == 'commission') {
                        $finalAmount = $order['order_amount']; // 结本金：只结本金
                    } else {
                        $finalAmount = $order['order_amount'] * 1; // 结本金+佣金：本金+10%佣金
                    }
                }
                
                error_log("订单 {$orderId} 结算: 类型={$dbSettlementType}, 金额={$finalAmount}, 操作类型={$operationType}");
                
                // 更新订单
                $updateSql = "UPDATE orders SET 
                    is_registered = 1, 
                    status = 'settled', 
                    settlement_type = ?, 
                    settlement_amount = ?, 
                    settlement_info = ?, 
                    admin_id = ?, 
                    updated_at = NOW() 
                    WHERE id = ?";
                
                $stmt = $db->prepare($updateSql);
                if (!$stmt->execute([$dbSettlementType, $finalAmount, $settlementInfo, $_SESSION['user_id'], $orderId])) {
                    throw new Exception("订单 {$orderId} 更新失败");
                }
                
                // 记录操作
                if (!recordOrderOperation($orderId, $operationType, $finalAmount, $settlementInfo, $uploadedScreenshots, $_SESSION['user_id'])) {
                    throw new Exception("订单 {$orderId} 操作记录失败");
                }
                
                // 处理结算记录
                processOrderSettlementNew($orderId, $settlementType, $finalAmount, $settlementInfo, $uploadedScreenshots, $_SESSION['user_id']);
                
                $successCount++;
                break;
                
            case 'mark_refunded':
                // 标记为已回款
                if ($order['is_refunded'] == 1) {
                    throw new Exception("订单 {$orderId} 已回款");
                }
                
                // 获取回款金额，如果未指定则使用结算金额
                $finalRefundAmount = $refundAmount;
                if (empty($finalRefundAmount)) {
                    $finalRefundAmount = $order['settlement_amount'] ?: $order['order_amount'];
                }
                
                // 更新订单回款状态
                $stmt = $db->prepare("UPDATE orders SET 
                    is_refunded = 1, 
                    refund_amount = ?, 
                    refund_info = ?, 
                    refund_screenshot = ?,
                    refunded_at = NOW(),
                    admin_id = ?, 
                    updated_at = NOW() 
                    WHERE id = ?");
                
                $refundScreenshotJson = !empty($uploadedScreenshots) ? json_encode($uploadedScreenshots) : null;
                
                if (!$stmt->execute([$finalRefundAmount, $refundInfo, $refundScreenshotJson, $_SESSION['user_id'], $orderId])) {
                    throw new Exception("订单 {$orderId} 回款状态更新失败");
                }
                
                // 记录操作 - 使用新的操作类型
                if (!recordOrderOperation($orderId, 'mark_refunded', $finalRefundAmount, $refundInfo, $uploadedScreenshots, $_SESSION['user_id'])) {
                    throw new Exception("订单 {$orderId} 操作记录失败");
                }
                
                $successCount++;
                break;
                
            case 'cancel_refund':
                // 取消回款
                if ($order['is_refunded'] == 0) {
                    throw new Exception("订单 {$orderId} 未回款");
                }
                
                $stmt = $db->prepare("UPDATE orders SET 
                    is_refunded = 0, 
                    refund_amount = NULL,
                    refund_info = NULL,
                    refund_screenshot = NULL,
                    refunded_at = NULL,
                    admin_id = ?, 
                    updated_at = NOW() 
                    WHERE id = ?");
                
                if (!$stmt->execute([$_SESSION['user_id'], $orderId])) {
                    throw new Exception("订单 {$orderId} 取消回款失败");
                }
                
                // 记录操作 - 使用新的操作类型
                if (!recordOrderOperation($orderId, 'cancel_refund', 0, '取消回款操作', [], $_SESSION['user_id'])) {
                    throw new Exception("订单 {$orderId} 操作记录失败");
                }
                
                $successCount++;
                break;
                
            default:
                throw new Exception("未知操作类型: {$action}");
        }
        
        // 提交事务
        $db->commit();
        
    } catch (Exception $e) {
        // 回滚事务
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $errors[] = $e->getMessage();
        $errorCount++;
        error_log("批量操作错误: " . $e->getMessage());
    }
}

$response = [
    'success' => $errorCount === 0,
    'message' => "操作完成：成功 {$successCount} 个，失败 {$errorCount} 个",
    'success_count' => $successCount,
    'error_count' => $errorCount,
    'errors' => $errors
];

echo json_encode($response);

/**
 * 删除订单及相关数据
 */
function deleteOrderAndRelatedData($orderId) {
    $db = getDB();
    
    // 获取订单信息
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    
    if (!$order) {
        return true;
    }
    
    // 删除相关图片
    if ($order['order_screenshot']) {
        deleteFile($order['order_screenshot'], 'order_screenshot');
    }
    if ($order['settlement_screenshot']) {
        deleteFile($order['settlement_screenshot'], 'settlement_screenshot');
    }
    if ($order['refund_screenshot']) {
        deleteFile($order['refund_screenshot'], 'settlement_screenshot');
    }
    
    // 删除操作记录中的图片
    $stmt = $db->prepare("SELECT screenshots FROM order_operations WHERE order_id = ?");
    $stmt->execute([$orderId]);
    $operations = $stmt->fetchAll();
    foreach ($operations as $op) {
        if ($op['screenshots']) {
            $screenshots = json_decode($op['screenshots'], true);
            if (is_array($screenshots)) {
                foreach ($screenshots as $screenshot) {
                    deleteFile($screenshot, 'settlement_screenshot');
                }
            }
        }
    }
    
    // 删除操作记录
    $stmt = $db->prepare("DELETE FROM order_operations WHERE order_id = ?");
    $stmt->execute([$orderId]);
    
    // 删除结算明细记录
    $stmt = $db->prepare("DELETE FROM settlement_details WHERE order_id = ?");
    $stmt->execute([$orderId]);
    
    // 删除订单
    $stmt = $db->prepare("DELETE FROM orders WHERE id = ?");
    return $stmt->execute([$orderId]);
}
?>